<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 开放城市
 *
 * @icon fa fa-circle-o
 */
class OpenCity extends Backend
{

    /**
     * OpenCity模型对象
     * @var \app\admin\model\deerhome\OpenCity
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\OpenCity;

    }

/**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['cityname']=trim($params['cityname']);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $cityArr=explode('/',$params['cityname']);
        if(count($cityArr)!=2){
            $this->error(__('请选择城市'));
        }
        $params['cityname']=trim($cityArr[1]);
        $params['province']=trim($cityArr[0]);
        $params['saas_hash']=md5($this->auth->id.$params['cityname']);
        $result = false;
        Db::startTrans();
        try {
            $this->model->validateFailException()->validate(
                ['saas_hash' => ['unique'=>'deerhome_open_city,cityname']],
			    ['saas_hash.unique'=> '城市已经存在，请更换']
            );
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


}
